package cn.tinlan.shopcoin.app.discover;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.CallClazzProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;
import com.zhouyou.http.subsciber.BaseSubscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.DensityUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.app.discover.adapter.ScrollLeftAdapter;
import cn.tinlan.shopcoin.app.discover.adapter.ScrollRightAdapter;
import cn.tinlan.shopcoin.app.discover.classify.ClassifyActivity;
import cn.tinlan.shopcoin.app.discover.model.DiscoverItemDataModel;
import cn.tinlan.shopcoin.base.BaseFragment;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;
import io.reactivex.Observable;

/**
 * Created by Mortimer on 2018/11/20. 15:01
 * 佛祖🙏，永无bug。
 */
public class DiscoverFragment extends BaseFragment {

    @BindView(R.id.dsearch_tv)
    TextView searchTV;
    @BindView(R.id.rec_left)
     RecyclerView recLeft;
    @BindView(R.id.rec_right)
     RecyclerView recRight;
    @BindView(R.id.right_title)
     TextView rightTitle;
    @BindView(R.id.discover_emptyview)
    View emptyView;
    @BindView(R.id.discover_empty_tv)
    TextView emptyTV;

    private List<DiscoverItemDataModel.ScrollItemBean> left;
    private List<DiscoverItemDataModel> right;
    private ScrollLeftAdapter leftAdapter;
    private ScrollRightAdapter rightAdapter;

    //右侧title在数据中所对应的position集合
    private List<Integer> tPosition = new ArrayList<>();
    //title的高度
    private int tHeight;
    //记录右侧当前可见的第一个item的position
    private int first = 0;
    private GridLayoutManager rightManager;

    private int tempPosition = 0;
    private boolean isFirst;

    @Override
    protected void onFragmentFirstVisible() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_discover;
    }

    @Override
    public void initView(View rootView) {
//        super.initView(rootView);
        initLeft();
        initRight();
        initEmptyView();
    }

    @Override
    protected void loadData() {


    }


    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible){

        }
    }

    private void initRight() {

        rightManager = new GridLayoutManager(mActivity, 3);

        if (rightAdapter == null) {

            recRight.setLayoutManager(rightManager);
            recRight.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    outRect.set(DensityUtils.dip2px(3)
                            , 0
                            , DensityUtils.dip2px(3)
                            , DensityUtils.dip2px(3));
                }
            });
            rightAdapter = new ScrollRightAdapter(mActivity,R.layout.scroll_right, R.layout.layout_right_title, null);
            recRight.setAdapter(rightAdapter);
        } else {
            rightAdapter.notifyDataSetChanged();
        }

        rightAdapter.setOnRightItemClickListener(new ScrollRightAdapter.OnRightItemClickListener() {
            @Override
            public void OnRightItemClickListener(String id, String title, int position) {
                Intent intent = new Intent(mActivity, ClassifyActivity.class);
                intent.putExtra("cate_id",id);
                intent.putExtra("title",title);
                getActivity().startActivity(intent);
            }
        });


        recRight.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //获取右侧title的高度
                tHeight = rightTitle.getHeight();

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (right == null || right.size() < 1) return;
                //判断如果是header
                if (right.get(first).isHeader) {
                    //获取此组名item的view
                    View view = rightManager.findViewByPosition(first);
                    if (view != null) {
                        //如果此组名item顶部和父容器顶部距离大于等于title的高度,则设置偏移量
                        if (view.getTop() >= tHeight) {
                            rightTitle.setY(view.getTop() - tHeight);
                            Log.i("height------>>>>",view.getTop() - tHeight+"");
                        } else {
                            //否则不设置
                            rightTitle.setY(0);
                        }
                    }
                }

                //因为每次滑动之后,右侧列表中可见的第一个item的position肯定会改变,并且右侧列表中可见的第一个item的position变换了之后,
                //才有可能改变右侧title的值,所以这个方法内的逻辑在右侧可见的第一个item的position改变之后一定会执行
                int firstPosition = rightManager.findFirstVisibleItemPosition();
                if (first != firstPosition && firstPosition >= 0) {
                    //给first赋值
                    first = firstPosition;
                    //不设置Y轴的偏移量
                    rightTitle.setY(0);

                    //判断如果右侧可见的第一个item是否是header,设置相应的值
                    if (right.get(first).isHeader) {
                        rightTitle.setText(right.get(first).header);
                    } else {
                        rightTitle.setText("");
                    }
                }

                //遍历左边列表,列表对应的内容等于右边的title,则设置左侧对应item高亮
                for (int i = 0; i < left.size(); i++) {
                    if (left.get(i).equals(rightTitle.getText().toString())) {
                        leftAdapter.selectItem(i);
                    }
                }

                //如果右边最后一个完全显示的item的position,等于bean中最后一条数据的position(也就是右侧列表拉到底了),
                //则设置左侧列表最后一条item高亮
//                if (rightManager.findLastCompletelyVisibleItemPosition() == right.size() - 1) {
//                    leftAdapter.selectItem(left.size() - 1);
//                    rightTitle.setText(left.get(left.size() - 1));
//                }
            }
        });
    }

    private void initLeft() {
        if (leftAdapter == null) {
            LinearLayoutManager llm = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
            recLeft.setLayoutManager(llm);
            recLeft.addItemDecoration(new DividerItemDecoration(mActivity, DividerItemDecoration.VERTICAL));
            leftAdapter = new ScrollLeftAdapter(R.layout.scroll_left, null);
            recLeft.setAdapter(leftAdapter);
        } else {
            leftAdapter.notifyDataSetChanged();
        }

        leftAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    //点击左侧列表的相应item,右侧列表相应的title置顶显示
                    //(最后一组内容若不能填充右侧整个可见页面,则显示到右侧列表的最底端)
                    case R.id.left_item:

                        if (tempPosition == position) return;
                        leftAdapter.selectItem(position);
                        rightTitle.setText(left.get(position).getName());
                        int pid = Integer.parseInt(left.get(position).getId());
                        getLeftData(pid);
                        tempPosition = position;
//                        rightManager.scrollToPositionWithOffset(tPosition.get(position), 0);
                        break;
                }
            }
        });
    }

    private void initEmptyView() {
        emptyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFirst = false;
                getLeftData(0);//左边列表请求
            }
        });
    }

    @Override
    public void initData() {
        super.initData();

//        right.add(new DiscoverItemDataModel(true, left.get(1)));
//        right.add(new DiscoverItemDataModel(new DiscoverItemDataModel.ScrollItemBean("2222222", left.get(1))));
//
//
//        for (int i = 0; i < right.size(); i++) {
//            if (right.get(i).isHeader) {
//                //遍历右侧列表,判断如果是header,则<>将此header在右侧列表中所在的position添加到集合中
//                tPosition.add(i);
//            }
//        }
//
//        rightAdapter.setNewData(right);

        getLeftData(0);//左边列表请求
    }

    //除了 0 即左边列表，其他的都根据左边item的 pid 来获取数据，
    private void getLeftData(final int pid) {


        Observable<List<DiscoverItemDataModel.ScrollItemBean>> observable = EasyHttp.get(Constants.GoodCategory)
                .params("pid",""+pid)
                .execute(new CallClazzProxy<CustomApiResult<List<DiscoverItemDataModel.ScrollItemBean>>, List<DiscoverItemDataModel.ScrollItemBean>>(new TypeToken<List<DiscoverItemDataModel.ScrollItemBean>>() {}.getType()) {
                });

        observable.subscribe(new BaseSubscriber<List<DiscoverItemDataModel.ScrollItemBean>>() {
            @Override
            public void onError(ApiException e) {
//                showToast(e.getMessage());
//                if ((e.getCode()+"").isEmpty()) {

//                    ToastUtils.show(e.getCode()+"");
                    if (left == null || left.size() < 1) {
                        if (emptyView.getVisibility() == View.GONE) {
                            emptyView.setVisibility(View.VISIBLE);
                        }
                    }
//                }

            }

            @Override
            public void onNext(List<DiscoverItemDataModel.ScrollItemBean> skinTestResult) {
//                showToast(skinTestResult.toString());

                if (pid == 0 && isFirst == false) {
                    for (int i = 0; i<skinTestResult.size();i++) {
                        DiscoverItemDataModel.ScrollItemBean  scrollItemBean= skinTestResult.get(i);

                        if (left == null) {
                            left = new ArrayList<>();
                        }
                        left.add(scrollItemBean);

                        if (right == null) {
                            right = new ArrayList<>();
                        }
//                        right.add(new DiscoverItemDataModel(true, scrollItemBean.getName()));

                        //遍历右侧列表,判断如果是header,则<>将此header在右侧列表中所在的position添加到集合中
                        tPosition.add(i);
                    }

                    if (left != null && left.size() > 0) {
                        leftAdapter.setNewData(left);
//                    rightAdapter.setNewData(right);
                        rightTitle.setText(left.get(0).getName());
                        isFirst = true;
                        emptyView.setVisibility(View.GONE);
                        int firstPid =  Integer.parseInt(left.get(0).getId());
                        getLeftData(firstPid);
                    }


                }else {
                    right.clear();
                    for (int i = 0; i<skinTestResult.size();i++) {
                        DiscoverItemDataModel.ScrollItemBean  scrollItemBean= skinTestResult.get(i);
                        if (i == 0) {
                            right.add(new DiscoverItemDataModel(true, left.get(pid).getName()));
                        }
                        right.add(new DiscoverItemDataModel(scrollItemBean));
                    }
                    rightAdapter.setNewData(right);
                }


            }

            @Override
            public void onComplete() {
                super.onComplete();


            }
        });
    }
}
